<template>
  <div class="font-sans">
    <!-- 初始加载动画 -->
    <InitialLoader />
            <div class="min-h-screen bg-slate-200 text-slate-800 relative overflow-hidden">
      <!-- 背景装饰 -->
      <div class="absolute bottom-0 left-0 w-full pointer-events-none">
        <img src="/wave-bg.svg" alt="" class="w-full" />
      </div>
      <div class="absolute top-0 right-0 w-full h-full pointer-events-none bg-repeat opacity-50" style="background-image: url('/dots-pattern.svg')">
      </div>
      <div class="container mx-auto p-4 relative">
          <!-- 装饰性图标 -->
          <div class="absolute -top-2 -right-2 opacity-30 pointer-events-none hidden md:block">
            <DecorativeIcon type="lightning" />
          </div>
          <div class="absolute -bottom-2 -left-2 opacity-30 pointer-events-none hidden md:block">
            <DecorativeIcon type="star" />
          </div>
        <header class="flex justify-between items-center mb-8 relative z-10">
          <div class="absolute -top-4 -left-4 w-20 h-20 rounded-full bg-indigo-500 opacity-10 blur-xl animate-pulse"></div>
          <div class="flex items-center">
            <NuxtLink to="/" class="text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-indigo-600 to-blue-500 hover:from-indigo-500 hover:to-purple-500 no-underline transition-all duration-300">
              新闻聚合平台
            </NuxtLink>
            <!-- 太阳系3D模型 - 完全独立，不影响主体布局 -->
            <div class="flex-shrink-0">
              <SolarSystem 
                ref="solarSystemRef"
                :key="'solar-system-header'"
                :visible="true"
                :size="80"
                :enable-animation="true"
                @ready="onSolarSystemReady"
                @error="onSolarSystemError"
              />
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <!-- 搜索框和切换按钮 -->
            <div class="relative group">
              <!-- 搜索输入框 -->
              <div class="relative">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索新闻..."
                  :class="[
                    'transition-all duration-300 search-mode',
                    isBreathing ? 'breathing' : ''
                  ]"
                  style="width: 480px;"
                  size="large"
                  clearable
                  @keyup.enter="handleSearch"
                  @clear="handleSearch"
                  @focus="handleSearchFocus"
                >
                  <template #prefix>
                    <el-button
                      link
                      size="small"
                      class="prefix-icon-btn"
                      @click="handlePrefixClick"
                    >
                      <el-icon class="text-slate-400 hover:text-slate-600 transition-colors duration-200 text-lg">
                        <Search v-if="searchMode === 'normal'" />
                        <ChatDotRound v-else />
                      </el-icon>
                    </el-button>
                  </template>
                  <!-- 隐藏切换按钮，保留搜索框的普通搜索功能 -->
                  <!-- <template #suffix>
                    <el-button
                      link
                      size="small"
                      class="mode-toggle-btn"
                      @click.stop="toggleSearchMode"
                    >
                      <el-icon class="text-blue-600 hover:text-blue-700 transition-all duration-300 transform hover:scale-125 hover:rotate-12 text-xl">
                        <Switch />
                      </el-icon>
                    </el-button>
                  </template> -->
                </el-input>
              </div>
            </div>

            <!-- 未登录状态：显示登录按钮 -->
            <NuxtLink 
              v-if="!isLoggedIn" 
              :to="loginLink" 
              class="text-slate-700 hover:text-slate-900 text-sm font-medium transition-colors duration-200"
            >
              登录
            </NuxtLink>
            
            <!-- 已登录状态：显示用户头像下拉菜单 -->
            <el-dropdown v-else trigger="click" class="user-dropdown">
              <div class="flex items-center cursor-pointer px-3 py-2 rounded-lg hover:bg-slate-100 transition-all duration-300">
                <el-avatar 
                  :size="32" 
                  :src="currentUser.avatar" 
                  class="mr-2"
                >
                  <el-icon><User /></el-icon>
                </el-avatar>
                <span class="text-sm font-medium text-slate-700">{{ currentUser.username }}</span>
                <el-icon class="ml-1 text-slate-500"><ArrowDown /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goToProfile">
                    <el-icon class="mr-2"><User /></el-icon>
                    个人中心
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleAdminClick">
                    <el-icon class="mr-2"><Setting /></el-icon>
                    后台管理
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">
                    <el-icon class="mr-2"><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            
            <!-- 智能助手下拉菜单 - 测试功能，暂时隐藏，后续开发 -->
            <!-- 
            <el-dropdown v-if="authReady" trigger="click" class="ai-assistant-dropdown">
              <el-button 
                class="chat-btn px-4 py-2 rounded-lg bg-blue-50 hover:bg-blue-100 text-blue-600 hover:text-blue-700 font-medium transition-all duration-300 hover:shadow-md transform hover:scale-105 border border-blue-200"
              >
                智能助手
                <el-icon class="ml-1"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openChat">
                    <el-icon class="mr-2"><ChatDotRound /></el-icon>
                    通用聊天
                  </el-dropdown-item>
                  <el-dropdown-item @click="openBiModal">
                    <el-icon class="mr-2"><Briefcase /></el-icon>
                    商业问答
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            -->

            <!-- 后台管理按钮 - 完全复制智能助手按钮的效果 -->
            <el-button 
              v-if="authReady"
              @click="handleAdminClick"
              class="admin-btn px-4 py-2 rounded-lg bg-blue-50 hover:bg-blue-100 text-blue-600 hover:text-blue-700 font-medium transition-all duration-300 hover:shadow-md transform hover:scale-105 border border-blue-200"
            >
              <el-icon class="mr-1"><Setting /></el-icon>
              后台管理
            </el-button>
          </div>
        </header>

        <nav class="mb-8 relative z-10">
          <el-menu
            mode="horizontal"
            :ellipsis="false"
            class="rounded-lg shadow-sm bg-slate-100 nav-categories"
            :default-active="activeCategory"
            @select="handleCategorySelect"
          >
            <el-menu-item index="all" class="font-medium">全部</el-menu-item>
            <el-menu-item
              v-for="cat in categories"
              :key="cat.id"
              :index="cat.code || String(cat.id)"
              class="font-medium"
            >
              {{ cat.name }}
            </el-menu-item>
          </el-menu>
        </nav>

        <main class="relative z-10">
          <PageTransition>
            <slot />
          </PageTransition>
        </main>
      </div>
      
      <!-- 聊天面板 -->
      <ChatPanel v-model="chatVisible" />
      <!-- 商业问答模态框 -->
      <BiModal v-model="biVisible" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, provide, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, ArrowDown, Setting, SwitchButton, Search, ChatDotRound, Switch, Briefcase } from '@element-plus/icons-vue'
import { categoryAPI } from '~/services/api'
import { useAuth } from '~/composables/useAuth'
import InitialLoader from '~/components/InitialLoader.vue'
import DecorativeIcon from '~/components/DecorativeIcon.vue'
import PageTransition from '~/components/PageTransition.vue'
import SolarSystem from '~/components/SolarSystem.vue'
import ChatPanel from '~/components/ChatPanel.vue'
import BiModal from '~/components/BiModal.vue'

// 使用认证管理
const { currentUser, isLoggedIn, logout, checkAuthValidity } = useAuth()

// 认证状态准备就绪标志
const authReady = ref(false)

// 登录链接（带重定向保留在当前页）
const loginLink = computed(() => `/admin/login?redirect=${encodeURIComponent(route.fullPath)}`)

// 分类选择
const activeCategory = ref('all')
const categories = ref([])
const handleCategorySelect = (index) => {
  activeCategory.value = index
}

// 搜索功能
const searchMode = ref('normal') // 'normal' | 'chat'
const searchKeyword = ref('')
const isBreathing = ref(false) // 控制呼吸灯效果

// 聊天面板 & 商业问答
const chatVisible = ref(false)
const biVisible = ref(false)

// 切换搜索模式
const toggleSearchMode = () => {
  searchMode.value = searchMode.value === 'normal' ? 'chat' : 'normal'
  searchKeyword.value = '' // 清空搜索关键词
  
  // 触发呼吸灯效果
  isBreathing.value = true
  setTimeout(() => {
    isBreathing.value = false
  }, 800) // 动画持续时间
}

// 处理搜索框聚焦
const handleSearchFocus = () => {
  // 触发呼吸灯效果
  isBreathing.value = true
  setTimeout(() => {
    isBreathing.value = false
  }, 800) // 动画持续时间
}

// 处理前缀图标点击
const handlePrefixClick = () => {
  // 搜索模式：跳转到首页
  if (searchMode.value === 'normal') {
    const kw = searchKeyword.value.trim()
    router.push(kw ? `/search?keyword=${encodeURIComponent(kw)}` : '/search')
  } else {
    // 智能对话模式：暂不跳转
    ElMessage({ message: '智能对话占位中', type: 'info', duration: 1200 })
  }
}

// 处理搜索
const handleSearch = () => {
  if (searchMode.value === 'normal') {
    // 普通搜索：跳转到搜索页
    const kw = searchKeyword.value.trim()
    router.push(kw ? `/search?keyword=${encodeURIComponent(kw)}` : '/search')
    return
  }
  // 智能对话：打开聊天面板
  if (searchKeyword.value.trim()) {
    openChat()
  }
}

// 打开聊天面板
const openChat = () => { chatVisible.value = true }

// 打开商业问答
const openBiModal = () => { 
  console.log('[BI] openBiModal clicked')
  biVisible.value = true 
}

// 提供分类状态给子组件
provide('activeCategory', activeCategory)

// 太阳系相关方法
const solarSystemRef = ref(null)

const onSolarSystemReady = (data) => {
  console.log('SolarSystem ready:', data)
}

const onSolarSystemError = (error) => {
  console.error('SolarSystem error:', error)
}

const loadCategories = async () => {
  try {
    const data = await categoryAPI.getCategories()
    categories.value = Array.isArray(data) ? data : []
  } catch (e) {
    console.error('加载分类失败:', e)
    categories.value = []
  }
}

// 检查登录状态
const checkLoginStatus = () => {
  // 使用认证管理检查登录状态有效性
  checkAuthValidity()
}

// 初始化
onMounted(() => {
  // 确保认证状态加载完成后再显示按钮
  nextTick(() => {
    checkLoginStatus()
    loadCategories()
    // 延迟一点时间确保认证状态完全加载
    setTimeout(() => {
      authReady.value = true
    }, 100)
  })
})

// 退出登录
const handleLogout = async () => {
  await logout()
  ElMessage({
    message: '已退出登录',
    type: 'info',
    duration: 1000
  })
  // 如果当前在管理后台页面，强制刷新跳转到首页
  if (route.path.startsWith('/admin')) {
    setTimeout(() => {
      localStorage.clear()
      sessionStorage.clear()
      window.location.href = '/'
    }, 1000)
  }
}

// 处理后台管理点击
const handleAdminClick = () => {
  // 使用认证管理检查登录状态
  if (isLoggedIn.value) {
    // 已登录，跳转到后台管理页面
    navigateTo('/admin/dashboard')
  } else {
    // 未登录，跳转到登录页面
    navigateTo('/admin/login')
  }
}

// 用户菜单操作
const goToProfile = () => {
  // 跳转到个人中心页面
  navigateTo('/profile')
}

const goToAdmin = () => {
  // 跳转到后台管理页面
  navigateTo('/admin')
}

// 这个logout函数已经被useAuth中的logout替代，可以删除

// 路由
const route = useRoute()
const router = useRouter()
</script>

<style scoped>
/* 用户下拉菜单样式 */
.user-dropdown {
  transition: all 0.3s ease;
}

.user-dropdown:hover {
  transform: translateY(-1px);
}

/* Element Plus 下拉菜单自定义样式 */
:deep(.el-dropdown-menu) {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--el-border-color-light);
}

:deep(.el-dropdown-menu__item) {
  padding: 8px 16px;
  font-size: 14px;
  transition: all 0.2s ease;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

:deep(.el-dropdown-menu__item.is-divided) {
  border-top: 1px solid var(--el-border-color-lighter);
  margin-top: 4px;
  padding-top: 8px;
}

/* 头像样式 */
:deep(.el-avatar) {
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.user-dropdown:hover :deep(.el-avatar) {
  border-color: var(--el-color-primary-light-5);
}
</style>

<style scoped>
/* 展开分类：允许横向菜单换行展示所有分类 */
:deep(.nav-categories.el-menu--horizontal) {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
}

/* 调整菜单项的内边距以适配多行布局 */
:deep(.nav-categories .el-menu-item) {
  padding: 0 12px;
  height: 40px;
  line-height: 40px;
}

/* 搜索框美化样式 */
:deep(.el-input__wrapper) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #cbd5e1;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
  border-color: #4f46e5;
}

/* 深色模式搜索框样式 */


/* 模式切换按钮样式 */
.mode-toggle-btn {
  opacity: 0.9;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 8px;
  padding: 6px;
  position: relative;
  overflow: hidden;
}

.mode-toggle-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.2), transparent);
  transition: left 0.6s ease;
}

.mode-toggle-btn:hover {
  opacity: 1;
  transform: scale(1.2);
  background-color: rgba(59, 130, 246, 0.15);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.mode-toggle-btn:hover::before {
  left: 100%;
}

.mode-toggle-btn:active {
  transform: scale(0.95);
  transition: transform 0.1s ease;
}

/* 搜索框聚焦时显示切换按钮 */
:deep(.el-input__wrapper.is-focus) .mode-toggle-btn {
  opacity: 1;
  background-color: rgba(59, 130, 246, 0.2);
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
}

/* 强制设置搜索框宽度 */
:deep(.el-input) {
  width: 480px !important;
}

/* 前缀图标按钮样式 */
.prefix-icon-btn {
  opacity: 0.8;
  transition: all 0.3s ease;
  border-radius: 6px;
  padding: 4px;
}

.prefix-icon-btn:hover {
  opacity: 1;
  transform: scale(1.1);
  background-color: rgba(100, 116, 139, 0.1);
}

/* 搜索框聚焦时显示前缀图标按钮 */
:deep(.el-input__wrapper.is-focus) .prefix-icon-btn {
  opacity: 1;
  background-color: rgba(100, 116, 139, 0.15);
}

/* 模式切换动画效果 */
.chat-mode :deep(.el-input__wrapper) {
  border-color: #8b5cf6;
  box-shadow: 
    0 0 0 3px rgba(139, 92, 246, 0.1),
    0 0 0 6px rgba(139, 92, 246, 0.05);
}

.search-mode :deep(.el-input__wrapper) {
  border-color: #3b82f6;
  box-shadow: 
    0 0 0 3px rgba(59, 130, 246, 0.1),
    0 0 0 6px rgba(59, 130, 246, 0.05);
}

/* 呼吸灯闪烁动画 - 渐变效果 */
@keyframes breathe {
  0% {
    box-shadow: 
      0 0 0 3px rgba(59, 130, 246, 0.1),
      0 0 0 6px rgba(59, 130, 246, 0.05);
  }
  50% {
    box-shadow: 
      0 0 0 3px rgba(59, 130, 246, 0.2),
      0 0 0 6px rgba(59, 130, 246, 0.1),
      0 0 0 9px rgba(59, 130, 246, 0.05),
      0 0 0 12px rgba(59, 130, 246, 0.03),
      0 0 0 15px rgba(59, 130, 246, 0.02),
      0 0 0 18px rgba(59, 130, 246, 0.01);
  }
  100% {
    box-shadow: 
      0 0 0 3px rgba(59, 130, 246, 0.1),
      0 0 0 6px rgba(59, 130, 246, 0.05);
  }
}

@keyframes breathe-chat {
  0% {
    box-shadow: 
      0 0 0 3px rgba(139, 92, 246, 0.1),
      0 0 0 6px rgba(139, 92, 246, 0.05);
  }
  50% {
    box-shadow: 
      0 0 0 3px rgba(139, 92, 246, 0.2),
      0 0 0 6px rgba(139, 92, 246, 0.1),
      0 0 0 9px rgba(139, 92, 246, 0.05),
      0 0 0 12px rgba(139, 92, 246, 0.03),
      0 0 0 15px rgba(139, 92, 246, 0.02),
      0 0 0 18px rgba(139, 92, 246, 0.01);
  }
  100% {
    box-shadow: 
      0 0 0 3px rgba(139, 92, 246, 0.1),
      0 0 0 6px rgba(139, 92, 246, 0.05);
  }
}

/* 切换时的呼吸灯效果 */
.search-mode.breathing :deep(.el-input__wrapper) {
  animation: breathe 0.8s ease-in-out;
}

.chat-mode.breathing :deep(.el-input__wrapper) {
  animation: breathe-chat 0.8s ease-in-out;
}

/* 切换按钮点击时的脉冲效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.mode-toggle-btn:active {
  animation: pulse 0.3s ease-in-out;
}

/* 智能助手下拉菜单样式 */
.ai-assistant-dropdown :deep(.el-dropdown-menu) {
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
  padding: 8px 0;
}

.ai-assistant-dropdown :deep(.el-dropdown-menu__item) {
  padding: 12px 16px;
  font-size: 14px;
  color: #374151;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.ai-assistant-dropdown :deep(.el-dropdown-menu__item:hover) {
  background-color: #f3f4f6;
  color: #1f2937;
}

.ai-assistant-dropdown :deep(.el-dropdown-menu__item.is-disabled) {
  color: #9ca3af;
  cursor: not-allowed;
}

.ai-assistant-dropdown :deep(.el-dropdown-menu__item.is-disabled:hover) {
  background-color: transparent;
}

/* 下拉箭头动画 */
.chat-btn .el-icon {
  transition: transform 0.2s ease;
}

.ai-assistant-dropdown:hover .chat-btn .el-icon:last-child {
  transform: rotate(180deg);
}
</style>